<template>
  <div class="dropdown" ref="dropdownRef">
    <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click="toggleOpen">你好 {{title}}</a>
    <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
      <li><router-link class="dropdown-item" :to="{ name: 'create' }">新建文章</router-link></li>
      <li><router-link class="dropdown-item" :to="{ name: 'column', params: { id: userId } }">我的专栏</router-link></li>
      <li><a class="dropdown-item" href="#">编辑资料</a></li>
      <li><router-link class="dropdown-item" :to="{ name: 'assembly' }">我的组件</router-link></li>
      <li><a class="dropdown-item" href="#" @click.prevent="loginOut">退出登录</a></li>
    </ul>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { GlobalDataProps } from './../store'
import useClickOutside from './../hooks/useClickOutside'
export default defineComponent({
  name: 'dropdown',
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup () {
    const store = useStore<GlobalDataProps>()
    const isOpen = ref(false)
    const dropdownRef = ref<null | HTMLElement>(null)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }
    const isClickOutside = useClickOutside(dropdownRef)
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside) {
        isOpen.value = false
      }
    })
    const loginOut = () => {
      store.commit('loginOut')
      location.reload()
    }
    const userId = computed(() => store.state.user.column)
    return {
      isOpen,
      toggleOpen,
      dropdownRef,
      loginOut,
      userId
    }
  }
})
</script>
